//
//  MTProvider+rx.swift
//  MT
//
//  Created by zhang qiang on 2019/4/28.
//  Copyright © 2019 DDC. All rights reserved.
//

import Foundation
import RxSwift
import ObjectMapper
import Result
import Moya


public typealias MTRequestResult<ModelType: Mappable> = (result:Result<ModelType, AnyError> , isCache:Bool)

public typealias MTOriginRequest = (result: Result<Response, AnyError>, isCache: Bool)

extension MTProvider: ReactiveCompatible {}

public extension Reactive where Base: MTProviderType {
    
    /// Designated request-making method.
    func originRequest(_ token: Base.Target, callbackQueue: DispatchQueue? = nil) -> Observable<MTOriginRequest> {
        return Observable.create { [weak base] observer in
            
            
            let cancellableToken = base?.originRequest(token, callbackQueue: callbackQueue, progress: nil, completion: { (result: Result<Response, AnyError>, isCache) in
                
                switch result {
                case let .success(response):
                    let ele = Result<Response, AnyError>.init(value: response)
                    observer.onNext( (ele, isCache) )
                case let .failure(error):
                    let ele = Result<Response, AnyError>.init(error: AnyError(error))
                    observer.onNext( (ele, isCache) )
                }
                
            })
            
            return Disposables.create {
                cancellableToken?.cancel()
            }
        }
    }
    
    
    func requestResult<ModelType: Mappable>(_ token: Base.Target, callbackQueue: DispatchQueue? = nil) -> Observable<MTRequestResult<ModelType>> {
        return Observable.create { [weak base] observer in
            
            
            let cancellableToken = base?.request(token, callbackQueue: callbackQueue, progress: nil, completion: { (result: Result<ModelType, AnyError>, isCache) in
                
                switch result {
                case let .success(response):
                    let ele = Result<ModelType, AnyError>.init(value: response)
                    observer.onNext( (ele, isCache) )
                    
                case let .failure(error):
                    let ele = Result<ModelType, AnyError>.init(error: AnyError(error))
                    observer.onNext( (ele, isCache) )
                    
                }
                
            })
            
            return Disposables.create {
                cancellableToken?.cancel()
            }
        }
        
    }
    
}
